package com.fhz.day006.live

import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.content.edit
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhz.day006.R
import com.fhz.day006.`fun`.User
import com.fhz.day006.`fun`.open
import com.fhz.day006.databinding.ActivityMain4Binding
import com.fhz.day006.sp.Main3ViewModel
import com.fhz.day006.sp.Main4ViewModel
import com.fhz.day006.sp.MyFactory4
import kotlinx.android.synthetic.main.activity_main4.*

class Main5Activity : AppCompatActivity() {


    lateinit var sp: SharedPreferences
    lateinit var viewModel: Main4ViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        setContentView(R.layout.activity_main4)
        val contentView =
            DataBindingUtil.setContentView<ActivityMain4Binding>(this, R.layout.activity_main4)
        contentView.user = User("小明",19)







        getSharedPreferences("data",MODE_PRIVATE).open {
            putString("name", "Tom")
            putInt("age", 28)
            putBoolean("married", false)
        }

        sp = getSharedPreferences("main4", MODE_PRIVATE)
        val edit = sp.edit()
        edit.putString("name", "Tom")
        edit.putInt("age", 28)
        edit.putBoolean("married", false)
        edit.apply()




        sp = getSharedPreferences("main4", MODE_PRIVATE)
        val i = sp.getInt("count", 0)

        viewModel = ViewModelProvider(this, MyFactory4(i)).get(Main4ViewModel::class.java)


        btn4.setOnClickListener {
//            viewModel.add()
            viewModel.mins()
        }

        //每一个viewModel中的livedata对象,都会有一个observe方法.
        // 用来观察数据的变化.并且自动更新.
        viewModel.count.observe(this,{
            tv4.text = it.toString()
            //
        })

        viewModel.s.observe(this, {

        })

    }

    override fun onPause() {
        super.onPause()
        sp.edit {
            putInt("count",viewModel.count.value ?: 0)
        }
    }
}
